<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="./data.js"></script>
  <style>
    .masonry{
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-auto-rows: 10px;/*代表网格一行的高度*/
      /* grid-template-rows: 1fr 1fr 1fr;会导致每一行的高度由内容说了算 */
      column-gap: 5px;
    }
    /* .item{
      grid-row-start: auto;
    } */
    img{
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="masonry">
      <img ref="imgRefs" v-for="item in images" :src="item.img" alt="">
    </div>
  </div>

  <script>
    const { createApp, ref, onMounted } = Vue
    createApp({
      setup() {
        const images = ref(data)
        const imgRefs = ref(null)// 获取图片元素，变量命名必须和img中ref""中的命名一样，并且必须是ref

        onMounted(() => { // 只会在页面渲染完成后执行
          imgRefs.value.forEach((item) => {
            let src = item.getAttribute('src')//获取src属性值
            let image = new Image()// 创造一个新的img标签，js中创建img不用createElement
            image.src = src// 给图片对象的src属性赋值浏览器就会加载图片
            let width = item.width
            // 防止页面上的img标签没有渲染完就执行下面代码
            image.onload = () => {
              let w = image.width
              let h = image.height
              let height = Math.round(width * h / w)// 计算出下边框跨越几行，round是四舍五入
              item.src = src
              item.style.gridRowEnd = `span ${~~(height / 10)}`// ~~向下取整
            }
          })  
        })


        return {
          images,
          imgRefs
        }
      }
    }).mount('#app')


  </script>  
</body>
</html>